package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionServerGroupDaoImpl extends TempDao {

    public void getServerGroupMap(Map<Integer, Map<Integer, CrossUnionServerGroup>> channelServerGroupMap, Map<Integer, CrossUnionServerGroup> serverGroupMap) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_cross_union_server_group order by groupId desc";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionServerGroup data = initServerGroup(rs);
                if(!channelServerGroupMap.containsKey(data.getChannelId())){
                    channelServerGroupMap.put(data.getChannelId(), new ConcurrentHashMap<>());
                }
                channelServerGroupMap.get(data.getChannelId()).put(data.getGroupId(), data);
                serverGroupMap.put(data.getGroupId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
    }

    private CrossUnionServerGroup initServerGroup(ResultSet rs) throws SQLException {
        CrossUnionServerGroup data = new CrossUnionServerGroup();
        data.setGroupId(rs.getInt("groupId"));
        data.setChannelId(rs.getInt("channelId"));
        data.setState(rs.getInt("state"));
        String value = rs.getString("serverList");
        data.setServerList(StringUtils.stringToLongList(value, ","));
        data.setChangTime(rs.getInt("changTime"));
        return data;
    }

    public Map<Integer, CrossUnionServerGroup> getServerGroupMap(int channelId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_cross_union_server_group where channelId = ?";
        Map<Integer, CrossUnionServerGroup> result = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            int i = 1;
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(i++, channelId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionServerGroup data = initServerGroup(rs);
                result.put(data.getGroupId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return result;
    }

}
